package net.yambal.android.geo;

import java.util.Locale;
import java.io.IOException;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import net.yambal.android.geo.db.TableFatAddressCatsh;
import net.yambal.android.util.RestUtil;
import net.yambal.android.util.StringUtil;

import android.content.Context;
import android.location.Geocoder;
import android.location.Address;
//import android.util.Log;

public class getFatAddress {
	public static String YAHOO_API_KEY = "yambal36";
	private Context _context;
	private TableFatAddressCatsh _table_fat_address_catsh;
	
	public getFatAddress(Context context){
		_context = context.getApplicationContext();
		_table_fat_address_catsh = TableFatAddressCatsh.getInstance(_context);
	}
	
	/**
	 * 文字列からDBを検索する
	 * @param context
	 * @param query
	 * @return
	 */
	public fatAddress getFromCatsh(fatAddressQuery query){
		fatAddress search_result;
		if(StringUtil.nullStrig(query.search_key ,null) != null){
			// キーワードで検索の場合
			search_result = _table_fat_address_catsh.searchOne(query.search_key, query.name_space);
		}else{
			// 座標で検索の場合
			search_result = _table_fat_address_catsh.searchOne(query.search_latetude, query.search_longitude, query.name_space);
		}
		if(search_result != null){
			return search_result;
		}
		return null;
	}
	
	/**
	 * fatAddressQueryからGoogle検索する
	 * @param context
	 * @param query
	 * @return
	 */
	public fatAddress getFromGoogle(fatAddressQuery query){
		Geocoder geo_cooder = new Geocoder(_context, Locale.JAPAN);
		if(StringUtil.nullStrig(query.search_key ,null) != null){
			//Log.i("sa", "getFatAddress.getFromGoogle(query.search_key):" + query.search_key);
			try {
				List<Address> addressies = geo_cooder.getFromLocationName(query.search_key, 1);
				if(addressies != null && addressies.size() > 0){
					Address address = addressies.get(0);
					fatAddress google = new fatAddress();
					google.source(address, -1L, query.name_space, query.search_key, false, query.save_extend_string);
					return google;
				}
			} catch (IOException e) {
				//Log.w("geo", "GEOUtil.GoogleGeo");
			}
		}else{
			//Log.i("sa", "getFatAddress.getFromGoogle(latlon):" + query.search_latetude + "," + query.search_longitude);
			
			// Yahooで住所を得る(nullかも)
			// 結局Googleの方が細かい様子
			//String yahoo_address = getYahooAddress(query.search_latetude, query.search_longitude);
			
			List<Address> addressies = null;
			try {
				addressies = geo_cooder.getFromLocation(query.search_latetude, query.search_longitude, 10);
			} catch (IOException e1) {
				//Log.e("sa", e1.getMessage());
				e1.printStackTrace();
			}
				
			if(addressies != null && addressies.size() > 0){
				int line_length = 0;
				fatAddress google = new fatAddress();
				
				while(addressies.size() != 0){
					Address address = addressies.remove(0);
					//Log.i("fa", "getFatAddress.getFromGoogle:" + address.toString() + "(" + address.getAddressLine(1) + ")");
					if(address.getAddressLine(1) != null && address.getAddressLine(1).length() > line_length){
						line_length = address.getAddressLine(1).length();
						//Log.i("fa", "getFatAddress.getFromGoogle:" + address.getAddressLine(1));
						google = new fatAddress();
						google.source(address, -1L, query.name_space, query.search_key, false, query.save_extend_string);
						
						if(query.keep_query_latlon){
							// 検索結果のLatLonは検索元と違うから戻す
							google.setLatitude(query.search_latetude);
							google.setLongitude(query.search_longitude);
						}
					}
				}

				google.search_key = StringUtil.nullStrig(google.getAddressLineCSV(), null);
				
				// 
				google.user_label = _table_fat_address_catsh.getUserLabelBySearchKey(google.search_key, query.name_space);
				return google;
			}
		}
		return null;
	}
	
	/**
	 * fatAddressQueryからDB検索、見つからなければGoogle検索
	 * @param context
	 * @param query
	 * @return
	 */
	public fatAddress get(fatAddressQuery query){	
		
		fatAddress catsh = getFromCatsh(query);
		if(catsh != null){
			return catsh;
		}
		
		fatAddress google = getFromGoogle(query);
		if(google == null){
			return null;
		}
		
		if(query.save_to_catsh){
			TableFatAddressCatsh table = TableFatAddressCatsh.getInstance(_context);
			table.save(google);
		}
		
		return google;
	}
	
	public static String getYahooAddress(Double latetude, Double longitude){
		String url = "http://reverse.search.olp.yahooapis.jp/OpenLocalPlatform/V1/reverseGeoCoder" +
				"?lat=" + String.valueOf(latetude) +
				"&lon=" + String.valueOf(longitude) +
				"&appid=" + YAHOO_API_KEY +
				"&output=json";
		//Log.i("sa", url);
		
		JSONObject root =  RestUtil.getJsonObj(url);
		if(root == null){
			//Log.w("sa", "json null");
			return null;
		}
		
		JSONArray feature = null;
		try {
			feature = root.getJSONArray("Feature");//getJSONObject("Feature");
		} catch (JSONException e) {
			//Log.w("sa", "feature null");
			return null;
		}
		
		JSONObject i = null;
		try {
			i = feature.getJSONObject(0);
		} catch (JSONException e) {
			//Log.w("sa", "item null");
			return null;
		}
		
		try {
			JSONObject property = i.getJSONObject("Property");
			String Address = property.getString("Address");
			return StringUtil.nullStrig(Address, null);
		} catch (JSONException e) {
			//Log.w("sa", "item null");
			return null;
		}
	}
}
